<template>
  <div>
    <!-- 悬浮按钮 -->
    <div class="chatbot-icon" @click="toggleDialog">
      <img src="../assets/img/avator.png" style="width:40px">
    </div>

    <!-- 聊天对话框 -->
    <el-dialog v-model="visible" title="AI 聊天助手" width="600px" :close-on-click-modal="true" :fullscreen="isFullscreen"
      :style="isFullscreen ? {} : { position: 'fixed', bottom: '40px', right: '20px' }">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>AI 聊天助手</span>
          <el-button type="text" @click="toggleFullscreen"
            style="padding:10px;position: absolute;top: 16px;right: 36px;"><el-icon>
              <FullScreen />
            </el-icon></el-button>
        </div>
      </template>

      <!-- 聊天记录 -->
      <div ref="chatContainer" class="chat-container">
        <div v-for="(message, index) in messages" :key="index" class="chat-message">
          <div :class="['message', message.role]">
            <!-- 系统角色，显示图标和内容 -->
            <template v-if="message.role === 'assistant'">
              <img src="../assets/img/1.png" style="width:40px; position: absolute; top: 0px;
    left: -50px;" />
              <span v-html="formattedContent(message.content)"></span>
            </template>
            <!-- 非系统角色，仅显示内容 -->
            <template v-else>
              <span v-html="formattedContent(message.content)"></span>
            </template>
          </div>
        </div>
        <!-- 等待提示 -->
        <div v-if="isThinking" class="chat-message">
          <div class="message assistant">
            <img src="../assets/img/1.png" style="width:40px; position: absolute; top: 0px;
    left: -50px;" />
            <el-icon>
              <Loading />
            </el-icon>
            正在思考...
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input">
        <el-input type="textarea" rows="4" v-model="input" placeholder="输入您的问题..." @keyup.enter.native="sendMessage" />
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { Loading } from '@element-plus/icons-vue';
import workApi from '../api/work';

const visible = ref(false); // 控制对话框的显示与隐藏
const input = ref(''); // 用户输入
const messages = ref([]); // 存储聊天记录
const isFullscreen = ref(false); // 控制是否全屏
const isThinking = ref(false); // 控制是否显示思考状态
const chatContainer = ref(null); // 引用聊天容器

// 切换对话框
const toggleDialog = () => {
  visible.value = !visible.value;
};

// 切换全屏模式
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
};

// 滚动到聊天容器底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  }
};

const username = sessionStorage.getItem('username') //日志需要
const currentConversationId = ref(null);
const sendMessage = async () => {
  if (!input.value.trim()) return;

  // 添加用户消息到 messages
  const userMessage = { role: 'user', content: input.value };
  messages.value.push(userMessage);

  // 清空输入框并显示思考状态
  const userInput = input.value;
  input.value = '';
  isThinking.value = true;

  // 滚动到底部
  nextTick(scrollToBottom);

  try {
    // 调用后端 API，传递完整的上下文和 conversationId
    const payload = {
      model: "deepseek-chat",
      messages: messages.value,
      username: username,
      conversationId: currentConversationId.value, // 当前对话 ID，初始为 null
    };

    const response = await workApi.handleAI(payload);

    // 更新对话 ID
    currentConversationId.value = response.data.conversationId;

    // 获取 AI 回复
    const aiMessage = { role: 'assistant', content: response.data.content };

    console.log(aiMessage)

    // 添加 AI 回复到 messages
    messages.value.push(aiMessage);
  } catch (error) {
    console.error('Error:', error);
    const errorMessage = { role: 'assistant', content: '发生错误，请稍后重试。' };
    messages.value.push(errorMessage);
  } finally {
    isThinking.value = false;
    nextTick(scrollToBottom);
  }
};

// 格式化内容，包括换行符的替换
const formattedContent = (content) => {
  return escapeHtml(content).replace(/\n/g, '<br>');
}

// 转义 HTML 特殊字符
const escapeHtml = (text) =>{
  return text.replace(/[&<>"'`]/g, (match) => {
    const escape = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;',
      '`': '&#96;' // 反引号的转义
    };
    return escape[match];
  });
}


</script>

<style scoped>
.chatbot-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: rgba(197, 194, 194, 0.78);
  color: #fff;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.chat-container {
  height: 500px;
  overflow-y: auto;
  padding: 10px;
  border-radius: 4px;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
}

.chat-message {
  display: flex;
  align-items: flex-end;
  margin-bottom: 10px;
}

.message {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  line-height: 1.5;
  word-wrap: break-word;
  font-size: 14px;
  position: relative;
  margin-left: 50px;
}

.message.assistant {
  background-color: #e9ecef;
  color: #333;
  align-self: flex-start;
}

.message.assistant::before {
  content: '';
  position: absolute;
  top: 10px;
  left: -8px;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-right-color: #e9ecef;
}

.message.user {
  background-color: #d1e7fd;
  color: #333;
  align-self: flex-end;
  margin-left: auto;
  /* 自动向左扩展 */
}

.message.user::before {
  content: '';
  position: absolute;
  top: 10px;
  right: -8px;
  width: 0;
  height: 0;
  border: 8px solid transparent;
  border-left-color: #d1e7fd;
}

.el-icon {
  margin-right: 5px;
  color: #888;
}

.chat-input {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.chat-input .el-input {
  flex: 1;
}

.chat-input .el-button {
  flex-shrink: 0;
}
</style>
